﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Marking
{
    public partial class Form1 : Form
    {
        string connectionString = "server=.;database=Watermarking;integrated security=SSPI;";
        string tableName;
        int lvOffset;
        int dbCnt;
        int len;

        string privateKey;
        int rowMod;
        int colMod;
        int bitMod;

        //------------------------------------------------------  控件大小随窗体大小变化
        private float X;
        private float Y;

        private Database_mag data_mag;

        public Form1()
        {
            InitializeComponent();
            lvOffset = 0;
            len = 2000;
            GetTables();
            comboBox1.Text = "weather";
            textBox4.Text = "98836117826371615331";
            //
            textBox1.Text = "11";
            textBox2.Text = "6";
            textBox3.Text = "5";
			textBox5.Text = "1";
			label8.Text = "";

			data_mag = new Database_mag();
        }
       

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        
        bool beginMove = false;//初始化鼠标位置
        int currentXPosition;
        int currentYPosition;

        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
                if (con.Controls.Count > 0)
                    setTag(con);
            }
        }

        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
                float a = Convert.ToSingle(mytag[0]) * newx;
                con.Width = (int)a;
                a = Convert.ToSingle(mytag[1]) * newy;
                con.Height = (int)(a);
                a = Convert.ToSingle(mytag[2]) * newx;
                con.Left = (int)(a);
                a = Convert.ToSingle(mytag[3]) * newy;
                con.Top = (int)(a);
                Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy);
                con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                if (con.Controls.Count > 0)
                {
                    setControls(newx, newy, con);
                }
            }

        }

        void Form1_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / X;
            float newy = this.Height / Y;
            setControls(newx, newy, this);
            this.Text = this.Width.ToString() + " " + this.Height.ToString();
        }
        //--------------------------------------------------------------------------   控件大小随窗体大小变化结束

        private void button3_Click(object sender, EventArgs e) //连接
		{

			tableName = comboBox1.Text.ToString();
			Preview(tableName);
			data_mag.Connection();
			button3.Enabled = false;
			comboBox1.Enabled = false;
			UpdateTip("数据库连接成功");

            //--------------------------------控件大小随窗体大小变化
            this.Resize += new EventHandler(Form1_Resize);

            X = this.Width;
            Y = this.Height;

            setTag(this);
            Form1_Resize(new object(), new EventArgs());
            //---------------------------------控件大小随窗体大小变化
        }

        private void button1_Click(object sender, EventArgs e) //添加水印
        {
            if (data_mag == null)
            {
                MessageBox.Show("请先连接数据库");
                return;
            }
            if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "")
            {
                MessageBox.Show("请完善必要参数");
                return;
            }
			button1.Enabled = false;
            rowMod = Convert.ToInt32(textBox1.Text);
            colMod = Convert.ToInt32(textBox2.Text);
            bitMod = Convert.ToInt32(textBox3.Text);
            privateKey = textBox4.Text;

			Thread th = new Thread(MarkTh);
			th.IsBackground = true;
			th.Start();
			
        }

		private void MarkTh()
		{
			Mark mark = new Mark();
			mark.ReturnProgress += new Mark.ReturnInt(UpdateProgress);
			mark.ReturnTip += new Mark.ReturnString(UpdateTip);
			mark.Mark_Click(data_mag, privateKey, rowMod, colMod, bitMod);
			UpdateProgress(0);
			UpdateTip("");
			lvOffset = 0;
			//Preview(tableName);
		}

        private void button2_Click(object sender, EventArgs e) //检测水印
        {
            if (textBox5.Text == "")
            {
                MessageBox.Show("检测参数不完整");
                return;
            }
			rowMod = Convert.ToInt32(textBox1.Text);
			colMod = Convert.ToInt32(textBox2.Text);
			bitMod = Convert.ToInt32(textBox3.Text);
			privateKey = textBox4.Text;

			Check check = new Check();
			check.CheckAlgorithm(data_mag, privateKey, rowMod, colMod, bitMod);
        }

		private void button4_Click(object sender, EventArgs e) //恢复数据
		{
			data_mag.Revert();
			MessageBox.Show("恢复完成");
			button1.Enabled = true;
			lvOffset = 0;
			Preview(tableName);
		}

		private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)  //下一页
		{
			lvOffset += len;
			if (lvOffset > dbCnt)
				return;
			Console.WriteLine("next" + lvOffset.ToString());
			Preview(tableName);
		}

		private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)  //上一页
		{
			lvOffset -= len;
			if (lvOffset < 0)
				return;
			Console.WriteLine("pre" + lvOffset.ToString());
			Preview(tableName);
		}

		private void GetTables()  //把可用数据表放在下拉列表中
        {
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            DataTable dt = con.GetSchema("Tables");
            con.Close();
            foreach (DataRow row in dt.Rows)
                comboBox1.Items.Add(row[2].ToString());
        }
        private void Preview(string tableName)  //预览表的内容
        {
            listView1.Items.Clear();
            listView1.Columns.Clear();
            string[] restriction = new string[4];
            int col_num = 0;
            restriction[2] = tableName;
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            DataTable dt = con.GetSchema("Columns", restriction);
            listView1.View = View.Details;
            foreach (DataRow row in dt.Rows)
            {
                listView1.Columns.Add(row["column_name"].ToString(), 80, HorizontalAlignment.Left);
                col_num++;
            }
            SqlCommand command = con.CreateCommand();
            command.CommandText = string.Format("SELECT COUNT(*) FROM {0}", tableName);
            dbCnt = Convert.ToInt32(command.ExecuteScalar());
            Console.WriteLine(dbCnt.ToString());
            command.CommandText = string.Format("SELECT TOP {2} * FROM {0} " +
                "where id not in (SELECT TOP {1} id FROM {0});", tableName, lvOffset, len);
            SqlDataReader reader = command.ExecuteReader();
            listView1.BeginUpdate();
            while (reader.Read())
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = reader.GetInt32(0).ToString();
                lvi.SubItems.Add(reader.GetInt32(1).ToString());
                lvi.SubItems.Add(reader.GetInt32(2).ToString());
                lvi.SubItems.Add(reader.GetInt32(3).ToString());
                lvi.SubItems.Add(reader.GetDateTime(4).ToString());
                lvi.SubItems.Add(reader.GetString(5));
                lvi.SubItems.Add(reader.GetDouble(6).ToString());
                lvi.SubItems.Add(reader.GetDouble(7).ToString());
                lvi.SubItems.Add(reader.GetDouble(8).ToString());
                lvi.SubItems.Add(reader.GetDouble(9).ToString());
                lvi.SubItems.Add(reader.GetDouble(10).ToString());
                lvi.SubItems.Add(reader.GetDouble(11).ToString());

                listView1.Items.Add(lvi);
            }
            reader.Close();
            con.Close();
            listView1.EndUpdate();
        }

		delegate void UpdateProDel(int v);
		public void UpdateProgress(int v)
		{
			if (progressBar1.InvokeRequired)
			{
				UpdateProDel d = new UpdateProDel(UpdateProgress);
				progressBar1.Invoke(d, new object[] { v });
			}
			else
			{
				progressBar1.Value = v;
			if (v == 0)
				label8.Text = "";
			else
				label8.Text = v.ToString() + "%";
			}

		}

		delegate void UpdateTipDel(string v);
		public void UpdateTip(string v)
		{
			if (label9.InvokeRequired)
			{
				UpdateTipDel d = new UpdateTipDel(UpdateTip);
				label9.Invoke(d, new object[] { v });
			}
			else
				label9.Text = v;
		}

		private void Form1_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (data_mag.tag != 0)
				data_mag.Revert();
		}

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            
            if (e.Button == MouseButtons.Left)
            {
                beginMove = true;
                currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标
                currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            
            if (beginMove)
            {
                this.Left += MousePosition.X - currentXPosition;//根据鼠标x坐标确定窗体的左边坐标x
                this.Top += MousePosition.Y - currentYPosition;//根据鼠标的y坐标窗体的顶部，即Y坐标
                currentXPosition = MousePosition.X;
                currentYPosition = MousePosition.Y;
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
           
            if (e.Button == MouseButtons.Left)
            {
                currentXPosition = 0; //设置初始状态
                currentYPosition = 0;
                beginMove = false;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void label5_Click(object sender, EventArgs e)
        {
            //--------------------------------控件大小随窗体大小变化
            this.Resize += new EventHandler(Form1_Resize);

            X = this.Width;
            Y = this.Height;

            setTag(this);
            Form1_Resize(new object(), new EventArgs());
            //---------------------------------控件大小随窗体大小变化
        }

        private void label7_Click(object sender, EventArgs e)
        {
            //--------------------------------控件大小随窗体大小变化
            this.Resize += new EventHandler(Form1_Resize);

            X = this.Width;
            Y = this.Height;

            setTag(this);
            Form1_Resize(new object(), new EventArgs());
            //---------------------------------控件大小随窗体大小变化
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }

}


